package com.lanchetech.service.impl;

import com.lanchetech.common.enums.SubscribeClientEnum;
import com.lanchetech.dao.FlashSaleSpuMapper;
import com.lanchetech.dao.SpuMapper;
import com.lanchetech.dao.SubscribeRecordMapper;
import com.lanchetech.dao.UserMapper;
import com.lanchetech.entity.*;
import com.lanchetech.service.AsyncNotifyService;
import com.lanchetech.service.JpushService;
import com.lanchetech.service.MiniAppMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AsyncNotifyServiceImpl implements AsyncNotifyService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    JpushService jpushService;

    @Autowired
    MiniAppMessageService miniAppMessageService;

    @Autowired
    SubscribeRecordMapper subscribeRecordMapper;

    @Autowired
    FlashSaleSpuMapper flashSaleSpuMapper;

    @Autowired
    SpuMapper spuMapper;

    @Async
    public void asyncAppNotify(List<Long> userIds, String activityName) {
        userIds.stream().forEach(item -> {
            User user = userMapper.selectByPrimaryKey(item);
            if (user.getRegisterId() != null) {
                jpushService.sendPushToPerson(activityName + "将在十分钟后开始", user.getRegisterId(), "秒杀订阅提醒", null);
            }
        });
    }

    @Async
    public void asyncMiniAppNotify(List<Long> userIds, FlashSaleActivity flashSaleActivity) {
        userIds.stream().forEach(item -> {
            User user = userMapper.selectByPrimaryKey(item);
            SubscribeRecord subscribeRecord = subscribeRecordMapper.findOneByActivityIdAndUserId(flashSaleActivity.getId(), item);
            FlashSaleSpu flashSaleSpu = flashSaleSpuMapper.selectByPrimaryKey(subscribeRecord.getRelateId());
            Spu spu = spuMapper.selectByPrimaryKey(flashSaleSpu.getSpuId());
            if (user.getOpenid() != null) {
                miniAppMessageService.sendFlashSaleSubscribeMessage(user.getOpenid(),flashSaleActivity,flashSaleSpu,spu.getMinPrice());
            }
        });
    }
}
